#include "wscaircraftsjson.h"
using namespace FsxWebService;

//
// Constructor
//
WscAircraftsJson::WscAircraftsJson(const int port, const QString &serverUrl, const QString &path, QObject *parent) :
    WscRequestHandler(port, serverUrl, path, parent)
{
    // constructor code
}

//
// Service of the web service
//
void WscAircraftsJson::service(HttpRequest& request, HttpResponse& response) {

    // set some headers
    response.setHeader("Content-Type", "application/json; charset=ISO-8859-1");
    response.setCookie(HttpCookie("wscaircrafts","aircrafts",600));

    // parameters
    JsonParameter parameter;
    bool isTest = false;
    QString callback; // used with JSONP
    WscAircraftsJson::getParameters(request, parameter, callback, isTest);

    // generate response
    // http://qt-project.org/faq/answer/how_can_i_convert_a_qstring_to_char_and_vice_versa
    QString dp = isTest ? "{\"running\": true}" : emit WscAircraftsJson::signalAircraftsJsonArray(parameter);
    if (dp.length() < 1) dp = "[]"; // empty array
    if (!callback.isEmpty())
    {
        dp = JsonMarkupHelper::jsonWrapInJsFunctionCall(0, callback, dp);
    }
    QByteArray ba = dp.toLocal8Bit();
    response.write(ba);
}

//
// Get the query parameters
//
void WscAircraftsJson::getParameters(HttpRequest &request, JsonParameter &parameter, QString &callback, bool &isTest)
{
    // requested just a test page
    isTest = Utils::stringToBoolean(request.getParameter("test"));
    callback = QString(request.getParameter("callback"));

    if (isTest) return;

    // resolve real parameters
    int waypointResolutionMs;
    QString res = QString(request.getParameter("waypointresolution"));
    bool validRes = !res.isEmpty() && (waypointResolutionMs=res.toInt(&validRes));
    if (!validRes) waypointResolutionMs = -1; // reset invalid values
    parameter.waypointResolutionPeriodMs = waypointResolutionMs;

    QString ww = QString(request.getParameter("withwaypoints"));
    parameter.withWaypoints = ww.isEmpty() ? true : Utils::stringToBoolean(ww);
}
